import Vue from 'vue'

const validatePrice = (rule, value, callback) => {
  if (/^\d+\.\d\d$/.test(value))
    callback();
  else
    callback(new Error('请输入数字值X.XX'));
};

const validateUnique = (rule, value, callback) => {
  let flag = true;
  params.paramProduct.customSize.forEach(function(item){
  if(item.name==value){
    flag=false;
    return;
   }
  })

  if(!flag){
    callback(new Error('重复的尺码'));
  }else{
    callback();
  }
};

const validateProductCode= (rule, value, callback) => { //产品编码校验
  let codeReg = /^[A-Za-z0-9\-]+$/;
  if(!codeReg.test(value)){
    callback(new Error('产品编号只能包含“英文字母、数字和-”！'));
  } else {
    callback();
  }
};

let colorTableColumn1 = function (self) {
  return {
    title: '综合操作',
    key: 'action',
    width:"220",
    render: (h, params) => {
      let str = '';
      switch (params.row.state){
        case 100:
          str = '下架';
          break;
        case 200:
          str = '上架';
          break;
        default:
          break;
      }
      return h('div', [
        h('Button', {
          props: {type: 'info', size: 'small', icon: "md-flash"},
          style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px', paddingTop: "4px",display: params.row.state == 300 ? 'none':''},
          on: {
            click: () => {
              self.upOrDownColorItem(params.index)
            }
          }
        }, params.row.state == 100 ? '下架' : "上架"),
        h('Button', {
          props: {type: 'primary', size: 'small', icon: "md-create"},
          style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px', paddingTop: "4px",display: params.row.state == 300 ? 'none':''},
          on: {
            click: () => {
              self.productColorModify(params.index);
            }
          }
        }, '编辑'),
        h('Button', {
          props: {type: 'error', size: 'small', icon: "md-trash"},
          style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px', paddingTop: "4px",display: params.row.state == 300 ? 'none':'' },
          on: {
            click: () => {
              self.deleteColorItem(params.index)
            }
          }
        }, '移入回收站'),
        h('Span', {
          style: {marginRight: '10px', marginTop:'6px',marginBottom:'6px',paddingTop: "4px",display: params.row.state != 300 ? 'none':'' },
        }, '请先从回收站找回')
      ]);
    },
    align: 'center'
  }
};

let sizeTableColumn= function (self) {
  return {
    title: '操作',
    key: 'action',
    render: (h, params) => {
      return h('Button', {
        props: {type: 'info', size: 'small', icon: "flash", disabled: !role.productSaleChange},
        style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px', paddingTop: "4px",},
        on: {
          click: () => {
            // self.upOrDownColorItem(params.index)
          }
        }
      }, "删除")
    },
    align: 'center'

  }
};

let status = {
  topTitle: '',//批量置顶的title
  topHidden: '',//批量置顶的开关
  saleTitle: '',//上下架的title
  selectImageType:0,//type 0:橱窗图 单   1:色卡样式图 单    2:试戴图单    3:明细图上传 多
  //查看图片
  modalImage: {
    isShow: false,
    url: ''
  },
  //查看图片
  modalImageSelect: {
    isShow: false,
    isLoading: false,
  },
  //各种操作时的 modal
  modalAction: {
    isShow: false,
    isLoading: false,
    title: '',
    content: '',
    type: 0,//0:删除 1:上下架 2:置顶 3:批量删除  4:批量上下架  5:批量置顶  6:批量添加标签 7:上下架色卡 8:删除色卡
    productColor: {
      productId: '',
      productCode:'',
      colorId: '',
      colorName:'',
      cnName:'',
      state:0 // 100 上架  200 下架 300 回收站
    }
  },
  //新增色卡时的 modal
  modalColorModify: {
    isShow: false,
    isLoading: false,
    title: '新增色卡',
  },
  modalModify: {
    isShow: false,
    isLoading: false,
    isShowCategory: false,
    isEditDetail: true,
    closable: true,
  },
  modalCustomSizeModify: {
    isShow: false,
    isLoading: true,
    title: '自定义尺码'
  },
  rules: {
    // productName: [
    //   {required: true, message: '产品名称不能为空', trigger: 'blur'}
    // ],
    productCode: [
      {required: true, message: '产品编号不能为空', trigger: 'blur'},
      {validator: validateProductCode, trigger: 'change'}
    ],
    sequence:[  {required: true, type: 'number', message: '请填写产品序号', trigger: 'blur'}],
    countWeight:[
      {required: true, type: 'number', message: '请填写产品计费重量', trigger: 'blur', min:1}
    ],
    // keyword:[  {required: true, message: '请填写搜索关键词', trigger: 'blur'}],
    priceUnit: [
      {required: true, type: 'number', message: '请选择计价单位', trigger: 'change'}
    ],
    productGender: [
      {required: true, type: 'number', message: '请选择适用性别', trigger: 'change'}
    ],
    showImage: [
      {required: true, type: 'object', message: '请选择橱窗图', trigger: 'change'}
    ],
    classificationIds: [
      {
        validator:(rule, value, callback)=>{
          if(value.length<=0){
            callback(new Error('请选择产品分类！'));
          }else{
            callback();
          }
        },
        trigger: 'change'
      }
    ],

    // add_product_interferenceFactor:[
    //   {required: true,type: 'number', message: '热度干扰因子不能为空', trigger: 'blur'}
    //
    // ],
    sysSizeType:[
      {required: true, type: 'number',message: '产品尺码类型不能为空', trigger: 'change'},
      {
        validator:(rule, value, callback)=>{
          if(value < 0){
            callback(new Error('产品尺码类型不能为空！'));
          }else{
            callback();
          }
        },
        trigger: 'change'
      }
    ],
    sysSizeIds:[
      {
        validator:(rule, value, callback)=>{
          if(value.length <= 0 && params.paramProduct.customSize.length <= 0){ //系统内置尺码或者自定义尺码全都没有时校验失败
            callback(new Error('产品尺码不能为空！'));
          }else{
            callback();
          }
        },
        trigger: 'change'
      }
    ]
  },
  colorRules: {
    colorName: [
      {required: true, message: '色卡名称不能为空', trigger: 'blur'}
    ],
    suggestedPrice: [
      {required: true, type:'float',message: '建议售价不能为空', trigger: 'blur'},
      {validator: validatePrice, trigger: 'blur'}
    ],
    currentPrice: [
      {required: true, type:'float',message: '当前售价不能为空', trigger: 'blur'},
      {validator: validatePrice, trigger: 'blur'}
    ],
    stock: [
      {type: 'integer', min: 0, message: '库存不能小于0', trigger: 'blur'},
      {type: 'integer', max: 999999999, message: '库存太长', trigger: 'blur'}
    ],
    iconImage: [
      {required: true,type:'object', message: '请选择色卡图标', trigger: 'blur'}
    ],
    colorImage: [
      {required: true,type:'object', message: '请选择色卡主图', trigger: 'blur'}
    ],
  },

  ruleCustomSize:{
    name: [
      {required: true, message: '尺码不能为空', trigger: 'blur'},
      { validator: validateUnique, trigger: 'blur' }
    ]
  },
  createTableModal:{
    isShow: false,
    isLoading: false,
    title: '确认重新生成表格吗？',
    content: '重新生成表格将清空现有尺码表数据',
  },
  supplyEditModal:{
    isShow : false,
    isNew : false
  },
  productOverstockModal:{
    isShow : false
  },
  isCheckDefaultDisabled: false //是否允许修改默认色卡checkbox
};

// 页面的数据源
let data = {
  //编辑详情的色卡
  productColorList: [],
  allTabs: [],
  allSysSize: [],
  allSysSizeMap:{},
  classificationTree:[],
  classificationList:[],
  productSizeDetail:[],
  classificationTreeShow:[],
  productColorSortList:[],
  productSupplyList:[],
  productOverstock:[],
  productOverstockSpan:[], //用于计算积压库存合并色卡列
  productImportInfo: {
    createTime: 0,
    createUser: "",
    profitRatio: 0,
    originInfo: {
      author: "",
      categories: [],
      prices: [],
      weight: 0,
    },
  },
};

let table = {
  colorTableTitles: {
    columnSequence: {
      title: '序号',
      key: 'sequence',
      width: 120,
      align: 'center'
    },
    columnColor: {
      title: '色卡名',
      key: 'colorName',
      width: 120,
      align: 'center'
    },
    columnIconImage: {
      title: '图标',
      key: 'colorImg',
      width: 100,
      align: 'center',
      render: (h, params) => {
        let yunPath = Vue.prototype.$store.getters.imgPrefix;
        let imageUrl = params.row.iconImage==null?"":(yunPath + params.row.iconImage.originalImagePath);
        return '' == imageUrl ? '' : h('img', {
          attrs: {src: imageUrl, height: 60},
          on: {
            click: () => {
              status.modalImage.url = imageUrl;
              status.modalImage.isShow = true;
            }
          }
        })
      },
    },
    columnColorImage: {
      title: '色卡主图',
      key: 'colorImg',
      width: 100,
      align: 'center',
      render: (h, params) => {
        let yunPath = Vue.prototype.$store.getters.imgPrefix;
        let imageUrl = params.row.colorImage==null?"":(yunPath + params.row.colorImage.originalImagePath);
        let img200w=imageUrl;
        if(params.row.colorImage!=null&&params.row.colorImage.zipImages!=null){
          let zipImage = eval(params.row.colorImage.zipImages);
          zipImage.forEach(function (item){
            if(item.size=="200w"){
              img200w=yunPath+item.imagePath;
            }
          })
        }
        return '' == imageUrl ? '' : h('img', {
          attrs: {src: img200w, height: 60},
          on: {
            click: () => {
              status.modalImage.url = imageUrl;
              status.modalImage.isShow = true;
            }
          }
        })
      },
    },
    columnDefault: {
      title: '是否默认',
      key: 'isDefault',
      width: 100,
      render: (h, params) => {
        return h('div',params.row.isDefault == 1 ? '是' : '否');
      },
      align: 'center'
    },
    columnState: {
      title: '状态',
      key: 'state',
      width: 100,
      render: (h, params) => {
        let state = '';
        if (params.row.state == 100) {
          state = '已上架';
        } else if (params.row.state == 200) {
          state = '已下架';
        } else {
          state = '回收站';
        }
        return h('div',state);
      },
      align: 'center'
    },
    columnDetailImgs: {
      title: '明细图',
      key: 'detailImgs',
      minWidth:380,
      render: (h, params) => {
        let yunPath = Vue.prototype.$store.getters.imgPrefix;
        let reusltImages = [];
        if ( params.row.detailImages&&params.row.detailImages.length>0) {
          params.row.detailImages.forEach(function (item) {
            reusltImages.push(h('li',
              [h('img', {
                style:{'padding-left':'5px','max-width':'80px'},
              attrs: {src: yunPath+item.originalImagePath},
              on: {
                click: () => {
                  status.modalImage.url = yunPath+item.originalImagePath;
                  status.modalImage.isShow = true;
                }
              }
            })]));
          });
        }
        return h('div',{style:{'overflow-x':'auto',width:'100%'}},[h('ul', {style: {display:'flex','list-style': 'none'}}, reusltImages)]);
      },
      align: 'center'
    },
    columnSizeStock: {
      title: '库存',
      key: 'sizeStock',
      width: 180,
      render: (h, params) => {
        let sizeStock = [];
        if ('' != params.row.sizes) {
          params.row.sizes.forEach(function (item) {
            sizeStock.push(h('li',
              [h('div', {
                style:{'padding-left':'5px','text-align': 'left'},
              },item.sizeName+':'+item.stock)]));
          });
        }
        return h('div',{style:{width:'100%'}},[h('ul', {style: { 'list-style':'none',margin: '0px',padding: '0px',}}, sizeStock)]);
      },
      align: 'center'
    },

    columnEdit1: colorTableColumn1,
  },
  sizeTableTitles: []
};

let productSupplyTable = function (self) {
  return [
    {
      type: 'index',
      title: '#',
      width: 60,
      key: 'index',
      fixed: 'left',
      align: 'center',
    },
    {
      title: '标题',
      key: 'name',
      width:  240,
      align: 'center'
    },
    {
      title: '采购渠道',
      key: 'source',
      width:  100,
      align: 'center',
      render: (h, params) => {
        let soureName;
        switch (params.row.source) {
          case 1:
            soureName = "1688";
            break;
          case 2:
            soureName = "淘宝";
            break;
          case 3:
            soureName = "拼多多";
            break;
          case 4:
            soureName = "线下";
            break;
          default:
            break;
        }
        return (<span>{soureName}</span>);
      }
    },
    {
      title: '采购链接',
      key: 'url',
      width: 220,
      align: 'center',
      render: (h, params) => {
        if (params.row.url.startsWith("http")) {
          return (
            <div>
              <a style="padding:6px;font-size:13px" target="_blank" href={params.row.url}>{params.row.url}</a>
            </div>
          );
        } else {
          return (
            <span></span>
          );
        }
      }
    },
    {
      title: '参考价格',
      key: 'referencePrice',
      width: 100,
    },
    {
      title: '货源店铺',
      key: 'shopName',
      width: 180,
      align: 'center',
    },
    // {
    //   title: '创建时间',
    //   key: 'createtime',
    //   width: 180,
    //   align: 'center',
    //   render: (h, params) => {
    //     let date = new Date(params.row.createtime);
    //   }
    // },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (h, params) => {
        return h('div', [
          h('Button', {
            props: {type: 'primary', size: 'small', icon: "md-create"},
            style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px'},
            on: {
              click: () => {
                self.editSupplyItem(params.row);
              }
            }
          }, '编辑'),
          h('Button', {
            props: {type: 'error', size: 'small', icon: "md-trash"},
            style: {marginRight: '10px',marginTop:'6px',marginBottom:'6px'},
            on: {
              click: () => {
                self.deleteSupplyItem(params.row.id)
              }
            }
          }, '删除')
        ]);
      }
    }
  ];
};

let productOverstockTable = function (self) {
  return [
    {
      type: 'index',
      title: '#',
      width: 60,
      key: 'index',
      fixed: 'left',
      align: 'center',
    },
    {
      title: '色卡',
      key: 'colorName',
      width:  140,
      align: 'center'
    },
    {
      title: '色卡图',
      key: 'colorImg',
      width:  100,
      align: 'center',
      render: (h, params) => {
        let yunPath = Vue.prototype.$store.getters.imgPrefix;
        return (<img height="60px" src={yunPath +params.row.colorImg}></img>);
      },
    },
    {
      title: '色卡状态',
      key: 'state',
      width:  140,
      align: 'center',
      render: (h, params) => {
        let state = '';
        if (params.row.state == 100) {
          state = '已上架';
        } else if (params.row.state == 200) {
          state = '已下架';
        } else {
          state = '回收站';
        }
        return (<div>{state}</div>);
      },
    },
    {
      title: '尺码',
      key: 'sizeName',
      width:  180,
      align: 'center'
    },
    {
      title: '系统库存',
      key: 'stock',
      width: 100,
      align: 'center'
    },
    {
      title: '积压库存',
      key: 'overstock',
      width: 140,
      render: (h, params) => {
        return h('Input', {
            props: {
              type: "number",
              value: params.row.overstock,
              min: 0
            },
            on: {
              "on-blur": event => {
                if(event.target.value <= 0){
                  event.target.value = 0;
                }
                self.tData.productOverstock[params.index].overstock = event.target.value;
              }
            }
          }
        );
      }
    }
  ];
};

// 和网络交互相关的参数
let params = {
  //查询相关
  productCode: "",
  gender: "",
  choosed_classify: "",
  orderBy: "",
  is_prefer: "0",//上下架
  isTop: true,//根据选择的产品得出 现在置顶的操作
  //选拔的产品
  products: [],
  //上传图片的folder
  uploadFolder: {},
  //当前选中的标签
  productTabs: 'product',
  customSize:{
    name:'',
    sequence:0
  },
  sysSizeTypeChange:0,
  //编辑
  paramProduct: {
    id: '',
    productName: '',
    isTop: false,
    productCode: '',
    classificationIds:[],
    sysSizeType:0,
    sysSizeIds:[],
    customSize:[],
    customSizeChecked:[],
    priceList:[
      {min:null,price:0},
      {min:null,price:0},
      {min:null,price:0}
    ],
    productState: -1,
    tab: '',
    manageTabIds: [],
    shelves:'',
    listImgUrl: '',
    productWeight: '',
    productMaterial: '',
    productGender: '',
    productIsUnisex: false,
    priceUnit: '',
    argJson: [
      {name: 'Weight', value: ''},
      {name: 'Material', value: ''}
    ],
    productSizeImages:[],
    sequence:10000,
    keyword:"",
    note:"",
    description:"",
    sizeTableType: 0, //0 无， 1手动生成， 2转换
    hasSizeTable:false, //是否启用尺码详情表
    useTranslateSizeTableTool: false,
    sizeTable: [],
    showImage: {}, //橱窗图
    showImage200w: {}, //橱窗图-200w压缩图
    mainImages: [], //主图
    detailImages: [], //详情图
    countWeight: null,
    comparePrice :{
      isUploadComparePrice: false,
      ratio:0,
      otherPrice:0,
      productPrice:0,
      images:[]
    },
    collectionId: "",
    videos:[]
  },
  productColor: {
    id: '',
    colorName: '',
    cnName: '',
    productId: '',
    productCode: '',
    colorImg: '',
    iconImg: '',
    state:100,
    description: '',
    isDefault: 0,
    detailImage: [],
    originalColorImg:"",
    colorSizeIds:[],
    productSizes:[],
    colorSizeSelected:[],
    iconImage:{},
    colorImage:{},
    detailImages:[],
  },
  productSizeTable:{
    columnCount:0,
    rowCount:0,
    title:'',
    subTitle:''
  },
  productSupply:{
    id:"",
    source:1,
    name:"",
    artno:"",
    url:"",
    referencePrice:0,
    priceRange:"",
    productId:"",
    shopName:"",
    state: 1,
    productCollectionId: "",
    productCollectionCode: "",
  },
  uploadFolderParam:{},
};

export  default  {
  tStatus: status,
  tParam: params,
  tData: data,
  tTable: table,
  productSupplyTable:productSupplyTable,
  productOverstockTable:productOverstockTable
};

